close all
NumOfStocks = 20;
NumOfBlocks = 10;
%[CovBlocks, Combinations, SampleSizes, Sigma, StockReturns]=GetCovBlocks(0);
load data_5_blocks.mat

noise = [1 2 5 4 2];
norms = {'fro', 1, 2};
error = zeros(length(norms), 10);
relative_error = zeros(length(norms), 9);

for iter=1:10,
    iter
    
    % Generate vectors for linear combinations
    for q = 1:length(CovBlocks),
        v{q} = [];
        for i=1:10,
            v{q} = [v{q} rand(length(Combinations{q}), 1)];
        end
    end
    
    for j=1:10,
        CovBlocksNoisy = addNoise(noise, CovBlocks);        
                
        for i=1:length(norms),
            cvx_begin
                cvx_quiet(true); 
                variable Sigma_hat(NumOfStocks, NumOfStocks) symmetric;
    
                %Define objective function
                f = 0;
                s_max = 0;
                for q=1:length(CovBlocksNoisy),
                    %Add the norm of differences between block covariance and the
                    %corresponding block in X.
                    f = f + norm(Sigma_hat(Combinations{q}, Combinations{q})-CovBlocksNoisy{q},norms{i});
                    
                    % Add linear combinations up to j
                    for m=1:j,
                        f = f + norm(v{q}(:,m)'*Sigma_hat(Combinations{q}, Combinations{q})*v{q}(:,m)-v{q}(:,m)'*CovBlocks{q}*v{q}(:,m),norms{i});
                    end
                    s_max = max(s_max, max(max(CovBlocksNoisy{q})));
                end
                
                minimize (f)
    
                subject to
                Sigma_hat == semidefinite(NumOfStocks)
                Sigma_hat(:) <= s_max;
                Sigma_hat(:) >= -s_max;
            cvx_end
    
            Sigmas_hat{i} = Sigma_hat;
            error(i, j) = error(i, j) + norm(Sigma_hat-Sigma, norms{i});
            if (j>1)
                relative_error(i, j-1) = relative_error(i,j-1) + (error(i, j)-error(i, 1))/error(i, 1);
            end
            %figure; hist(Sigmas_hat{i}(:)-Sigma(:));
        end
    end
end

error = error/10;
relative_error = relative_error/10;